const express = require('express');
const { failure, success } = require('../../utils/responses');
const router = express.Router();
const { Attachment, User } = require('../../models');
const { findListPagination } = require('../../utils/pagination');
const { client } = require('../../utils/aliyun');
/**附件管理列表 */
router.get('/', async (req, res) => {
  try {
    const attachment = await findListPagination(req.query, (pagination) =>
      Attachment.findAndCountAll({
        ...pagination,
        include: [
          {
            model: User,
            as: 'user',
            attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
          },
        ],
      })
    );
    success({ res, data: attachment });
  } catch (error) {
    failure({ res, error });
  }
});

/**
 * 删除附件
 * DELETE /admin/attachments
 */
router.delete('/:id', async function (req, res) {
  try {
    const attachment = await getAttachment(req);

    // 删除阿里云OSS中的文件
    await client.delete(attachment.fullpath);

    // 删掉数据库中的附件记录
    await attachment.destroy();

    success({ res, message: '删除附件成功。' });
  } catch (error) {
    failure({ res, error });
  }
});
/**
 * 公共方法：查询当前附件
 */
async function getAttachment(req) {
  const { id } = req.params;

  const attachment = await Attachment.findByPk(id);
  if (!attachment) {
    throw new NotFound(`ID: ${id}的附件未找到。`);
  }

  return attachment;
}

module.exports = router;
